import axios, { AxiosRequestConfig } from 'axios';
import Cookies from 'js-cookie';

// 创建axios实例
const instance = axios.create({
  baseURL: '/api',
  timeout: 30000,  // 30秒超时
  withCredentials: true
});

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const token = Cookies.get('token');
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`;
    }

    // 只在开发环境打印请求日志
    if (process.env.NODE_ENV === 'development') {
      console.log('发送请求:', {
        url: config.url,
        method: config.method,
        data: config.data
      });
    }

    return config;
  },
  error => {
    console.error('请求错误:', error);
    return Promise.reject(error);
  }
);

// 响应拦截器
instance.interceptors.response.use(
  response => {
    const res = response.data;

    // 只在开发环境打印响应日志
    if (process.env.NODE_ENV === 'development') {
      console.log('收到响应:', {
        url: response.config.url,
        status: response.status,
        code: res.code
      });
    }

    if (res.code !== 200) {
      // 不在拦截器中显示错误消息，让调用方决定
      if (res.code === 401) {
        Cookies.remove('token');
        // 避免在已经在登录页面时重复跳转
        if (!window.location.pathname.includes('/login')) {
          window.location.href = '/login';
        }
      }
      return Promise.reject(new Error(res.message || '请求失败'));
    }

    return res;
  },
  error => {
    console.error('响应错误:', {
      url: error.config?.url,
      status: error.response?.status,
      message: error.response?.data?.message
    });

    // 处理网络错误和HTTP状态码错误
    if (error.response?.status === 401) {
      Cookies.remove('token');
      if (!window.location.pathname.includes('/login')) {
        window.location.href = '/login';
      }
    }

    return Promise.reject(error);
  }
);

const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
  return instance(config);
};

// 封装GET请求
export function get<T>(url: string, params?: any, config?: AxiosRequestConfig) {
  return request<T>({ url, method: 'get', params, ...config });
}

// 封装POST请求
export function post<T>(url: string, data?: any, config?: AxiosRequestConfig) {
  return request<T>({ url, method: 'post', data, ...config });
}

// 封装PUT请求
export function put<T>(url: string, data?: any, config?: AxiosRequestConfig) {
  return request<T>({ url, method: 'put', data, ...config });
}

// 封装DELETE请求
export function del<T>(url: string, config?: AxiosRequestConfig) {
  return request<T>({ url, method: 'delete', ...config });
}

// HTTP方法辅助函数
request.get = <T = any>(url: string, params?: any, config?: AxiosRequestConfig): Promise<T> => {
  return request({ ...config, method: 'get', url, params });
};

request.post = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return request({ ...config, method: 'post', url, data });
};

request.put = <T = any>(url: string, data?: any, config?: AxiosRequestConfig): Promise<T> => {
  return request({ ...config, method: 'put', url, data });
};

request.delete = <T = any>(url: string, config?: AxiosRequestConfig): Promise<T> => {
  return request({ ...config, method: 'delete', url });
};

export default request; 